package dj.framework.aspect;

import com.commons.utils.RequestHolder;
import com.commons.utils.SecurityUtils;
import com.commons.utils.StringUtils;
import com.commons.utils.ThrowableUtil;
import dj.framework.domain.SysLog;
import dj.framework.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class LogAspect {

    private final Logger LOGGER= LoggerFactory.getLogger(LogAspect.class);

    ThreadLocal<Long> currentTime=new ThreadLocal<>();

    private final SysLogService sysLogService;

    @Autowired
    public LogAspect(SysLogService sysLogService) {
        this.sysLogService = sysLogService;
    }

    @Pointcut("@annotation(dj.framework.annotation.Log)")
    public void logPointcut()
    {

    }

    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
        Object result=null;
        currentTime.set(System.currentTimeMillis());
        result=joinPoint.proceed();
        SysLog sysLog = new SysLog("INFO", System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        sysLogService.save(getUserName(), StringUtils.getBrowser(request),StringUtils.getIp(request),joinPoint,sysLog);
        return result;
    }

    @AfterThrowing(pointcut = "logPointcut()",throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e){
        SysLog sysLog = new SysLog("ERROR",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        sysLog.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes());
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        sysLogService.save(getUserName(), StringUtils.getBrowser(request),StringUtils.getIp(request), (ProceedingJoinPoint) joinPoint,sysLog);
    }

    private String getUserName(){
        try {
            return SecurityUtils.getCurrentUser().getUsername();
        }catch (Exception e){
            return "";
        }

    }
}
